﻿using Bystd.Geo.Converters;
using Bystd.Geo.Geometries;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bystd.Geo.GeoParsers.SpatiaLite
{
    public class GeometryWriter
    {
        private Geometry geometry = null;
        private BitExtensions bitExt = null;
        private Wkb.GeometryWriter wkbWrite = null;

        public GeometryWriter(Geometry geometry)
        {
            this.geometry = geometry;
            bitExt = new BitExtensions(ByteOrder.LittleEndian);
            wkbWrite = new Wkb.GeometryWriter(bitExt.ByteOrder, false);
        }

        public byte[] Writer()
        {
            using (var ms = new MemoryStream())
            using (var bm = new BinaryWriter(ms))
            {
                bm.Write((byte)BlobMark.MARK_START);
                bm.Write((byte)EndianMark.LITTLE_ENDIAN);

                bm.Write(bitExt.GetBytes(this.geometry.SRID));

                var box= geometry.GetBoundrayBox();
                bm.Write(bitExt.GetBytes(box.Start.X));
                bm.Write(bitExt.GetBytes(box.Start.Y));

                bm.Write(bitExt.GetBytes(box.End.X));
                bm.Write(bitExt.GetBytes(box.End.Y));

                bm.Write((byte)BlobMark.MARK_MBR);

                //geometry
                WriteGeometry(bm);

                bm.Write((byte)BlobMark.MARK_END);
        
                return ms.ToArray();
            }
        }

        private void WriteGeometry(BinaryWriter binWrite)
        {
            var geo_buffer= wkbWrite.Writer(geometry);
            binWrite.Write(geo_buffer);
        }
    }
}
